package middleware

import (
	"github.com/gin-gonic/gin"
	v1 "server_go/api/v1"
	"server_go/pkg/jwt"
)

// RequireRole 返回一个中间件，要求用户具备指定角色才能访问
func RequireRole(requiredRole int8) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		claims, exists := ctx.Get("claims")
		if !exists {
			v1.HandleError(ctx, 401, v1.ErrUnauthorized, nil)
			ctx.Abort()
			return
		}

		myClaims, ok := claims.(*jwt.MyCustomClaims)
		if !ok || myClaims.UserType != requiredRole {
			v1.HandleError(ctx, 403, v1.ErrForbidden, nil)
			ctx.Abort()
			return
		}

		ctx.Next()
	}
}
